import 'dart:io';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../config.dart';
import '../core/utils/image_crop_page.dart';
import '../viewmodel/login_view_model.dart';

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  bool _obscureText = true;
  String? _localImagePath;      // 本地头像路径
  String? _uploadedAvatarUrl;   // 服务器上传后头像地址
  final String _defaultAvatarUrl = '${Config.baseUrl}/files/default.jpg';

  final _usernameController = TextEditingController();
  final _passwordController = TextEditingController();

  @override
  void initState() {
    super.initState();
    _loadLocalImagePath();
  }

  // 加载本地头像路径（App重启后保留）
  Future<void> _loadLocalImagePath() async {
    final prefs = await SharedPreferences.getInstance();
    final path = prefs.getString('localImagePath');
    if (path != null && File(path).existsSync()) {
      setState(() {
        _localImagePath = path;
      });
    }
  }

  // 保存裁剪后图片到本地，并存储路径
  Future<void> _saveCroppedImage(File cropped) async {
    final dir = await getApplicationDocumentsDirectory();
    final savedFile = await cropped.copy('${dir.path}/avatar.png');
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString('localImagePath', savedFile.path);
    setState(() {
      _localImagePath = savedFile.path;
    });
  }

  String getRelativePath(String url) {
    if (url.startsWith(Config.baseUrl)) {
      return url.substring(Config.baseUrl.length);
    }
    return url;
  }

  ImageProvider _getAvatarImage() {
    // 启动总是先显示默认头像
    if (_uploadedAvatarUrl != null && _uploadedAvatarUrl!.isNotEmpty) {
      // 上传成功且有网络头像，显示网络头像
      return NetworkImage('${Config.baseUrl}$_uploadedAvatarUrl');
    } else {
      // 默认头像
      return const AssetImage('assets/images/default.jpg');
    }
  }

  @override
  Widget build(BuildContext context) {
    final vm = context.watch<LoginViewModel>();

    return Scaffold(
      resizeToAvoidBottomInset: false,
      body: Center(
        child: SizedBox(
          height: 600,
          width: 300,
          child: Column(
            children: [
              const SizedBox(height: 50),
              const Text(
                'I  M',
                style: TextStyle(fontSize: 35, fontWeight: FontWeight.bold),
              ),
              const SizedBox(height: 30),
              Form(
                child: Column(
                  children: [
                    GestureDetector(
                      onTap: () async {
                        final File? cropped = await Navigator.push(
                          context,
                          MaterialPageRoute(builder: (_) => const ImageCropPage()),
                        );

                        // 保存并上传头像
                        if (cropped != null) {
                          await _saveCroppedImage(cropped);
                          final uploadedUrl = await vm.upload(cropped);
                          if (uploadedUrl.isNotEmpty) {
                            setState(() {
                              _uploadedAvatarUrl = uploadedUrl;
                            });
                          }
                        }

                      },
                      child: CircleAvatar(
                        radius: 40,
                        backgroundImage: _getAvatarImage(),
                        child: const Align(
                          alignment: Alignment.bottomRight,
                          child: Icon(Icons.camera_alt, size: 20, color: Colors.white70),
                        ),
                      ),
                    ),
                    const SizedBox(height: 30),
                    _buildInputField(
                      label: '用户名',
                      hint: '请输入用户名',
                      controller: _usernameController,
                    ),
                    const SizedBox(height: 20),
                    _buildInputField(
                      label: '密码',
                      hint: '请输入密码',
                      controller: _passwordController,
                      obscureText: _obscureText,
                      suffixIcon: IconButton(
                        icon: Icon(
                          _obscureText ? Icons.visibility_off : Icons.visibility,
                          color: Colors.grey,
                        ),
                        onPressed: () {
                          setState(() {
                            _obscureText = !_obscureText;
                          });
                        },
                      ),
                    ),
                    const SizedBox(height: 20),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        _buildActionButton('注册', () async {
                          final username = _usernameController.text.trim();
                          final password = _passwordController.text.trim();

                          // 注册时传头像URL，优先上传后的，否则默认头像URL
                          final avatarUrl = _uploadedAvatarUrl ?? getRelativePath(_defaultAvatarUrl);

                          await vm.register(username: username, password: password, avatar: avatarUrl);
                        }),
                        _buildActionButton('登录', () async {
                          final username = _usernameController.text.trim();
                          final password = _passwordController.text.trim();

                          await vm.login(username: username, password: password);
                        }),
                      ],
                    )
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildInputField({
    required String label,
    required String hint,
    required TextEditingController controller,
    bool obscureText = false,
    Widget? suffixIcon,
  }) {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        boxShadow: const [
          BoxShadow(color: Colors.black12, blurRadius: 8, offset: Offset(0, 4)),
        ],
      ),
      child: TextField(
        controller: controller,
        obscureText: obscureText,
        decoration: InputDecoration(
          labelText: label,
          hintText: hint,
          filled: true,
          fillColor: Colors.white,
          contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
          border: OutlineInputBorder(
            borderSide: BorderSide.none,
            borderRadius: BorderRadius.circular(12),
          ),
          suffixIcon: suffixIcon,
        ),
      ),
    );
  }

  Widget _buildActionButton(String text, VoidCallback onPressed) {
    return ElevatedButton(
      style: ElevatedButton.styleFrom(
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(13)),
        minimumSize: const Size(90, 45),
      ),
      onPressed: onPressed,
      child: Text(text),
    );
  }
}
